#include <iostream>
#include <string>
#include <cstring>
#include <memory>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "log.hpp"
#include "thread.hpp"

std::string ip;
uint16_t port;

void Usage(std::string proc)
{
    std::cout << "\nUsage" << proc << " port\n" << std::endl;
}

void* Send(void* argv)
{
    int sock = *(int*)((ThreadData*)argv)->_args;
    std::string name = ((ThreadData*)argv)->_name;

    // 定义套接字结构体,把发送的信息填进去
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    while (true)
    {
        std::string message;
        std::getline(std::cin, message);
        if (message == "quit") break;
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));
    }
}

void* Recv(void* argv)
{
    int sock = *(int*)((ThreadData*)argv)->_args;
    std::string name = ((ThreadData*)argv)->_name;

    // 定义套接字结构体,填写信息并进行读取
    char buffer[1024];
    while(true)
    {
        memset(&buffer, 0, sizeof(buffer));

        struct sockaddr_in tmp;
        memset(&tmp, 0, sizeof(tmp));
        socklen_t len = sizeof(tmp);
        ssize_t s = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr*)&tmp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << buffer << std::endl;
        }
    }
}

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        Usage(argv[1]);
        exit(1);
    }

    // 1.定义 套接字
    ip = argv[1];
    port = atoi(argv[2]);
    int sock = socket(AF_INET, SOCK_DGRAM, 0);  // 定义套接字
    if (sock < 0)
    {
        logMessage(FATAL, "%d: %s", errno, strerror(errno));
        exit(2);
    }

    // 2.定义两个线程分别接受数据和发送数据
    std::unique_ptr<Thread> sender(new Thread(1, Send, (void*)&sock));
    std::unique_ptr<Thread> recver(new Thread(2, Recv, (void*)&sock));

    sender->start();
    recver->start();

    sender->join();
    recver->join();

    close(sock);
    return 0;
}